// pages/operationStatistics/operationStatistics.js
const app = getApp();
import * as echarts from '../../ec-canvas/echarts';
import CommonService from '../../utils/service/commonService.js';
const util = require('../../utils/util');

//图表对象
let Chart1=null;
let Chart2=null;
let Chart3=null;
let Chart4=null;

//去掉尾部的0
const regexp=/(?:\.0*|(\.\d+?)0+)$/;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //图表
    ec1: {
      //延迟加载
      lazyLoad: true
    },
    ec2: {
      lazyLoad: true
    },
    ec3: {
      lazyLoad: true
    },
    ec4: {
      lazyLoad: true
    },
    //是否显示图表（避免弹框遮挡）
    showChart:true,
    //无数据
    showNoData1:false,
    showNoData2:false,
    showNoData3:false,
    showNoData4:false,
    //图表配置
    chartSet1:{
      //圆柱颜色
      barColor:'#035E9B',
      //y轴标题
      title:'（分）'
    },
    chartSet2:{
      barColor:'#035E9B',
      title:'（小时）'
    },
    chartSet3:{
      barColor:'#035E9B',
      title:''
    },
    chartSet4:{
      barColor:'#035E9B',
      title:''
    },
    //设置使用率
    showUseRate:false,
    //使用率相关数据
    minValue: 20,
    maxValue: 80,
    //时间跨度
    showTimeSpan:false,
    //时间跨度相关数据
    minValue2: 0,
    maxValue2: 23,
    //今日日期
    todayDate:util.timeFormatDay(new Date()),
    //日期选择框
    showDate:false,
    currentDate: new Date().getTime(),
    minDate: new Date().getTime(),
    maxDate: new Date().getTime(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      } else if (type === 'month') {
        return `${value}月`;
      }
      return value;
    },
    //显示的日期
    currentDateStr:util.timeFormatDay(new Date()),
    //选择周
    showWeek:false,
    //周的选择列表
    weekList:[],
    //显示的周
    weekWord:'本周',
    //选中的周
    selectedWeek:{
      start:'',
      end:''
    },
    //日统计到几天前
    dayNum:7,
    //周统计到几周前
    weekNum:7,
    //传参
    paramObj:{},
    //用户权限
    authority: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      authority: app.globalData.authority
    })
    
    //设置日统计的最小日期
    this.getBeforeDate();

    //计算本周和上几周的日期
    this.getWeekList();

    if(options.paramObj){
      let paramObj=JSON.parse(options.paramObj);
      console.log('工作时段传参');
      console.log(paramObj);

      this.setData({
        paramObj:paramObj
      })

      //日统计数据
      this.getDayData();

      //周统计数据
      this.getWeekData();
    }
  },

  //日统计数据
  getDayData(){
    this.setData({
      showNoData1:false,
      showNoData3:false
    })

    //图表组件
    this.echartsComponnet1 = this.selectComponent('#mychart1');
    //图表组件
    this.echartsComponnet3 = this.selectComponent('#mychart3');

    //清空数据
    let chartData={
      xData:[],
      yData:[]
    }

    let chartData2={
      xData:[],
      yData:[]
    }

    //查询参数
    let param={
      imei:this.data.paramObj.imei,
      rangeTag:"hour",
      begin:this.data.currentDateStr,
      end:this.data.currentDateStr
    }

    CommonService.getRunTimeByDateRange(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        console.log('日数据');
        console.log(result);

        result.forEach(item => {
          //分钟数
          let num=(item.totalRunTime.value/1000/60).toFixed(1);
          //小时数
          let numH=item.totalRunTime.value/1000/60/60;

          if(Number(num)){
            chartData.xData.push(parseInt(item.key_as_string.slice(11,13)));
            chartData2.xData.push(parseInt(item.key_as_string.slice(11,13)));

            chartData.yData.push(num.replace(regexp,'$1'));
            chartData2.yData.push(parseInt(Number(numH)*this.data.paramObj.workAmount));
          }
        });

        console.log('图表数据-日');
        console.log(chartData);
        console.log(chartData2);

        if(!chartData.yData.length){
          this.setData({
            showNoData1:true
          })
        }

        if(!chartData2.yData.length){
          this.setData({
            showNoData3:true
          })
        }

        //判断图表是否第一次绘制
        this.isHaveChart(Chart1,this.echartsComponnet1,this.data.chartSet1,chartData);
        this.isHaveChart(Chart3,this.echartsComponnet3,this.data.chartSet3,chartData2);
      }else{
        this.setData({
          showNoData1:true,
          showNoData3:true
        })
      }
    }).catch((error) => {
    })
  },

  //周统计数据
  getWeekData(){
    this.setData({
      showNoData2:false,
      showNoData4:false
    })

    //图表组件
    this.echartsComponnet2 = this.selectComponent('#mychart2');
    this.echartsComponnet4 = this.selectComponent('#mychart4');

    //清空数据
    let chartData={
      xData:[],
      yData:[]
    }

    let chartData2={
      xData:[],
      yData:[]
    }

    //查询参数
    let param={
      imei:this.data.paramObj.imei,
      rangeTag:"day",
      begin:this.data.selectedWeek.start,
      end:this.data.selectedWeek.end
    }

    CommonService.getRunTimeByDateRange(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        console.log('周数据');
        console.log(result);

        result.forEach(item => {
          let num=(item.totalRunTime.value/1000/60/60).toFixed(1);
          console.log(num);
          //如果超过24则取23.6
          if(Number(num)>=24.0){
            num = "24.0";
          }

          if(Number(num)){
            //日期转化为周
            let day=new Date(item.key_as_string.slice(0,10).replaceAll("-","/"));
            chartData.xData.push(util.timeFormatWeek(day));
            chartData2.xData.push(util.timeFormatWeek(day));

            //图表数据中加入日期，用于点击事件的传参
            let yObj={
              date:util.timeFormatDay(day),
              value:num.replace(regexp,'$1'),
              chart2:true
            }
            chartData.yData.push(yObj);

            let yObj2={
              date:util.timeFormatDay(day),
              value:parseInt(Number(num)*this.data.paramObj.workAmount)
            }
            chartData2.yData.push(yObj2);
          }
        });

        console.log('图表数据-周');
        console.log(chartData);
        console.log(chartData2);

        if(!chartData.yData.length){
          this.setData({
            showNoData2:true
          })
        }
        if(!chartData2.yData.length){
          this.setData({
            showNoData4:true
          })
        }

        //判断图表是否第一次绘制
        this.isHaveChart(Chart2,this.echartsComponnet2,this.data.chartSet2,chartData);
        this.isHaveChart(Chart4,this.echartsComponnet4,this.data.chartSet4,chartData2);
      }else{
        this.setData({
          showNoData2:true,
          showNoData4:true
        })
      }
    }).catch((error) => {
    })
  },

  //判断图表是否第一次绘制
  isHaveChart(chartObj,componnetObj,setObj,dataObj){
    if (!chartObj){
      //如果是第一次绘制，则初始化图表
      this.init_echarts(chartObj,componnetObj,setObj,dataObj);
    }else{
      //更新图表数据
      this.setOption(chartObj,setObj,dataObj);
    }
  },

  //初始化图表
  init_echarts: function (chartObj,componnetObj,setObj,dataObj) {
    componnetObj.init((canvas, width, height) => {
      chartObj = echarts.init(canvas, null, {
        width: width,
        height: height
      });

      this.setOption(chartObj,setObj,dataObj);

      return chartObj;
    });
  },

  //更新图表数据
  setOption: function (chartObj,setObj,dataObj) {
    //清除
    chartObj.clear();
    //设置新数据
    chartObj.setOption(this.getOption(chartObj,setObj,dataObj));
  },

  //指定图表的配置项和数据
  getOption: function (chartObj,setObj,dataObj) {
    //文字颜色
    let fontColor='#333';
    let _this=this;

    let option = {
      grid: {
        left: '2%',
        right: '2%',
        top: '20%',
        bottom: '5%',
        containLabel: true,
      },
      xAxis: {
        type: 'category',
        axisLabel: {
          color: fontColor,
          fontSize : 13,
          interval:0
        },
        axisLine: {
          lineStyle: {
            color: setObj.barColor
          }
        },
        data: dataObj.xData,
      },
      yAxis: {
        type: 'value',
        name: setObj.title,
        axisLabel: {
          color: fontColor,
          fontSize : 14,
        },
        axisLine: {
          lineStyle: {
            color: setObj.barColor
          }
        },
        splitLine: {
          lineStyle: {
            color: '#eee'
          }
        }
      },
      series: [{
        barWidth : '15px',
        data: dataObj.yData,
        type: 'bar',
        label:{
          normal:{
            fontSize:14,
            rich:{}
          }
        },
        itemStyle:{
          normal:{
              label:{
                  show:true,
                  position:'top',
                  color:fontColor,
                  formatter: function(params) {
                    return params.value;
                  },
              },
              color: setObj.barColor
          }
        }   
      }]
    };

    //首先移除事件，不然会造成多次点击
    chartObj.off('click');
    //点击柱状图
    chartObj.on('click', function (params) {
      //点击周统计图表
      if(params.data.chart2){
        _this.setData({
          currentDateStr: params.data.date
        })
        //日统计数据
        _this.getDayData();
      }
    })

    return option;
  },

  //隐藏图表
  hideChart(){
    this.setData({
      showChart:false
		})
  },

  //显示图表
  showChart(){
    this.setData({
      showChart:true
		})
  },

  //设置日统计的最小日期
  getBeforeDate(){
    let rusult=util.countPrevDay(new Date(),this.data.dayNum);
    this.setData({
			minDate: rusult
		})
  },

  //显示日期选择框
  onShowDate(){
    this.setData({
      showDate: true
    })
    //隐藏图表
    this.hideChart();
  },

  //关闭日期选择框
  onCloseDate(){
    this.setData({
      showDate: false
    })
    //显示图表
    this.showChart();
  },

  //确定日期时
  onConfirmDate(event){
    this.setData({
      currentDate: event.detail,
      currentDateStr:util.timeFormatDay(event.detail)
    })

    //关闭日期选择框
    this.onCloseDate();

    //请求日统计数据
    this.getDayData();
  },

  //显示设置时间跨度
  onShowTimeSpan(){
    this.setData({
      showTimeSpan: true
    })
    //隐藏图表
    this.hideChart();
  },

  //隐藏设置时间跨度
  onCloseTimeSpan(){
    this.setData({
      showTimeSpan: false
    })
    //显示图表
    this.showChart();
  },

  //确认时间跨度
  onConfirmTimeSpan(){
    //隐藏设置时间跨度
    this.onCloseTimeSpan();

    //请求日统计数据
    this.getDayData();
  },

  //显示设置使用率
  onShowUseRate(){
    this.setData({
      showUseRate: true,
      showChart:false
		})
  },

  //隐藏设置使用率
  onCloseUseRate(){
    this.setData({
      showUseRate: false,
      showChart:true
		})
  },

  //滑动选择使用率
  onRangeChange: function(e) {
    this.setData({
      minValue: Math.round(e.detail.minValue),
      maxValue: Math.round(e.detail.maxValue)
    });
  },

  //滑动选择时间跨度
  onRangeChange2: function(e) {
    this.setData({
      minValue2: Math.round(e.detail.minValue),
      maxValue2: Math.round(e.detail.maxValue)
    });
  },

  //计算本周和上几周的日期
  getWeekList(){
    //当前日期
    let today=new Date();
    let day = today.getDay() || 7;
    //本周周一
    let monday=new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1 - day);
    //本周周日
    let sunday=new Date(today.getFullYear(), today.getMonth(), today.getDate() + 7 - day);

    //周统计初始参数赋值
    this.setData({
      selectedWeek:{
        start:util.timeFormatDay(monday),
        end:util.timeFormatDay(today)
      }
		})

    //本周
    let weekList=[{
      text:util.timeFormatDay(monday) +' 至 '+ util.timeFormatDay(today),
      start:util.timeFormatDay(monday),
      end:util.timeFormatDay(today),
      word:util.timeFormatDay(monday).slice(5) +' 至 '+ util.timeFormatDay(today).slice(5)
    }];

    let n=this.data.weekNum;
    for(let i=1;i<=n;i++){
      let lastMonday=util.countPrevDay(monday,7);
      let lastSunday=util.countPrevDay(sunday,7);
      let obj={
        text:util.timeFormatDay(lastMonday) +' 至 '+ util.timeFormatDay(lastSunday),
        start:util.timeFormatDay(lastMonday),
        end:util.timeFormatDay(lastSunday),
        word:util.timeFormatDay(lastMonday).slice(5) +' 至 '+ util.timeFormatDay(lastSunday).slice(5)
      }
      weekList.push(obj);
    }

    this.setData({
      weekList: weekList
		})
  },

  //显示选择周的日期
  onShowWeekSelect(){
    this.setData({
			showWeek: true
    })
    //隐藏图表
    this.hideChart();
  },

  //隐藏选择周的日期
  onCloseWeek(){
    this.setData({
			showWeek: false
    })
    //显示图表
    this.showChart();
  },

  //确认选择周的日期
  onConfirmWeek(e){
    let obj=e.detail.value;
    this.setData({
      weekWord: obj.word,
      selectedWeek:obj
    })

    //隐藏选择周的日期
    this.onCloseWeek();

    //请求周统计数据
    this.getWeekData();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})
